import React, { PureComponent, Fragment } from 'react';
import { Spin, Row, Col, Card, Checkbox, Select, Button , message } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './print.less';
import {abs} from '@/utils/utils';

const { Option } = Select;

@connect(({ deliverManage, loading,global }) => ({
  storeName:global.oemInfo.storeName,
  orderDeliverList:deliverManage.orderDeliverList,
  printItemConfig:deliverManage.printItemConfig,
  loading: loading.effects['deliverManage/GetOrderPrintList'],
  loadingPrintItem: loading.effects['deliverManage/GetPrintItemConfig'],
}))
//@Form.create()
export default class LoanSettleMent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      printItem:[1,2,3,4],
      fontSize:14
    };
  }

  componentDidMount() {
    // const code = !isEmptyObject(this.props.match) ? this.props.match.params.id : 0;
    // this.statisticalInfo({ receiptsCode: code });
    const {match} = this.props;
    console.log(this.props)
    this.requestList(match.params.ids);
    this.getPrintItem(match.params.ids);
    window.Isoption = true;
  }

  componentWillUnmount(){
    window.Isoption = false;
    this.setState = (state, callback) => {
      return
    }
  }

  // 订单列表详情
  requestList= (params) => {
    this.props.dispatch({
      type: 'deliverManage/GetOrderPrintList',
      payload: {
        OrderIds:params
      },
      callback:{        
        error:(data)=>{
          if(data.Code !=0){
            router.replace({
              pathname: `/exception/404`,
            });
          }
        }
      }
    })
  }

  // 获取打印选项配置
  getPrintItem = (ids) => {
    this.props.dispatch({
      type: 'deliverManage/GetPrintItemConfig',
      payload: {
        OrderIds:ids
      },
      callback:{
        success:(data)=>{
          this.setState({
            printItem:data.Data.PrintItem||[1,2,3,4],
            fontSize:data.Data.FontSize||14
          })
        },
        error:()=>{

        }
      }
    })
  }


  // 标记已打印发货单
  markPrinted = (params) =>{
    const {match} = this.props;
    const {printItem,fontSize} = this.state;
    this.props.dispatch({
      type: 'deliverManage/PrintedInvoice',
      payload: {
        OrderIdList:match.params.ids.split(','),
        PrintItem:printItem,
        FontSize:fontSize
      },
      callback:{
        success:(data)=>{
          console.log(data)
          message.success('操作成功')
         
        },
        error:(data) =>{
          console.log(data)
          message.error('操作失败')
        }
      }
    })
  }

  // 撤销操作
  fetchRevocation(params) {
    this.props
      .dispatch({
        type: 'finance/fetchRevocation',
        payload: params,
      })
      .then(() => {
        const { finance: { revocationData } } = this.props;
        const { code } = revocationData;
        if (code === 200) {
          message.info('撤销货款单成功!').then(() => {
            window.location.href = '/funds/loansettlement';
          });
        } else {
          message.info('撤销货款单失败!');
        }
      });
  }

  // 撤销
  cancer = () => {
    const code = !ithis.props.match ? this.props.match.params.id : 0;
    this.fetchRevocation({
      receiptsCode: code,
    });
  };

  // 返回
  back = () => {
    window.history.back();
  };

  // 打印
  print(){
    this.markPrinted();
    window.document.body.innerHTML = window.document.getElementById('billDetails').innerHTML;  
    window.print(); 
    window.location.reload();
  }

  selectPrintItem = (e) => {
    console.log(e)
    this.setState({
      printItem:e
    });    
  }

  ChangeFontSize = (e) => {
    this.setState({
      fontSize:e
    }); 
  }

  isShow = (num) => {
    const { printItem } = this.state;
    return printItem.indexOf(num)>-1;
  }

  calcSpan = () =>{
    const { printItem } = this.state;
    if(printItem.indexOf(1)>-1&&printItem.indexOf(3)>-1){
      return 6;
    }else{
      if(printItem.indexOf(1)<0&&printItem.indexOf(3)>-1){
        return 9;
      }else if(printItem.indexOf(1)>-1&&printItem.indexOf(3)<0){
        return 10;
      }else{
        return 13;
      }
    }
  }

  render() {
    const { orderDeliverList,loadingPrintItem,loading,storeName } = this.props;
    const { printItem,fontSize } = this.state;
    return (
      <Fragment>
        <Spin spinning={loadingPrintItem&&loading}>  
          <div className="xkd-bg-fff">   
          <Card bordered={false} className={styles.PrintTitle} >
            <Row>
              <Col>
                打印选项：
                <Checkbox.Group onChange={this.selectPrintItem} value={printItem}>
                  <Checkbox value={1}>打印单价</Checkbox>
                  <Checkbox value={2}>打印总价</Checkbox>
                  <Checkbox value={3}>商品留言</Checkbox>
                  <Checkbox value={4}>规格</Checkbox>
                </Checkbox.Group>
                字号：
                <Select value={fontSize} onChange={this.ChangeFontSize}>
                  <Option value={12}>12px</Option>
                  <Option value={13}>13px</Option>
                  <Option value={14}>14px</Option>
                  <Option value={15}>15px</Option>
                  <Option value={16}>16px</Option>
                </Select>
              </Col>
            </Row>
          </Card>
          <Row>
            <Col  className={styles.printInfoBox}>
              <div id={'billDetails'} style={{minWidth:fontSize>14?726:680}}>
                {
                  orderDeliverList&&orderDeliverList.map((item,index)=>{
                    return ( 
                      <Card bordered={false} className={styles.OrderInfo} style={{pageBreakAfter: "always"}} key={index}>
                        <Row type="flex" justify="space-between">
                          <Col span={8} style={{fontSize:fontSize}}>{storeName}</Col>
                          <Col span={7} style={{textAlign:'center',fontSize:'18px'}}>商品发货单</Col>
                          <Col span={9} style={{fontSize:fontSize}}>
                            <Row>
                              <Col span={8} style={{textAlign:'right',padding:0,}}>订单号：</Col>
                              <Col span={16} style={{padding:0}}>{item.OrderNo}</Col>
                            </Row>
                            <Row>
                              <Col span={8} style={{textAlign:'right',padding:0,width:81}}>下单时间：</Col>
                              <Col span={16} style={{padding:0}}> {item.CreateTime}</Col>
                            </Row>                  
                          </Col>
                        </Row>
                        <Row>
                          <Col span={6} style={{fontSize:fontSize}}>收货人：{item.Receiver}</Col>
                          <Col span={6} style={{fontSize:fontSize}}>联系方式：{item.ReceiverPhone}</Col>
                          <Col span={12}>
                            <Row>
                              <Col span={5} style={{textAlign:'right',padding:0,fontSize:fontSize,whiteSpace: "nowrap"}}>收货地址：</Col>
                              <Col span={19} style={{textAlign:'left',padding:0,fontSize:fontSize}}>{item.FullAddress}</Col>
                            </Row>
                          </Col>
                        </Row>
                        <Row className={styles.OrderInfoHead}>
                          <Col span={2} style={{fontSize:fontSize}}>序号</Col>
                          <Col span={3} style={{fontSize:fontSize}}>商品编码</Col>
                          <Col span={this.calcSpan()} style={{fontSize:fontSize,textAlign:'left',paddingLeft:16}}>商品名称{this.isShow(4)?'/规格':''}</Col>                          
                          {
                            this.isShow(1)?<Col span={3} style={{fontSize:fontSize}}>单价(元)</Col> :null
                          }                                                                            
                          <Col span={2} style={{fontSize:fontSize}}>数量</Col>                          
                          {
                            this.isShow(3)?<Col span={4} style={{fontSize:fontSize,textAlign:'left',paddingLeft:16}}>商品留言</Col> :null
                          } 
                          <Col span={4} style={{fontSize:fontSize,textAlign:'left',paddingLeft:16}}>维权信息</Col>
                        </Row>
                        {
                          item.OrderItems&&item.OrderItems.map((v,i)=>{
                            return (  
                              <Row className={styles.OrderInfobody} key={i}>
                                <Col span={2} style={{fontSize:fontSize}}>{i+1}</Col>
                                <Col span={3} style={{fontSize:fontSize}}>{v.SkuCode}</Col>
                                <Col span={this.calcSpan()} style={{fontSize:fontSize}}>
                                  <div className="xkd-text-ellipsis-2" style={{fontSize:fontSize}}>
                                    {v.ProductName}
                                  </div>                                  
                                  {
                                    this.isShow(4)?<div className="xkd-text-ellipsis" style={{fontSize:fontSize}}>{v.SkuName}</div>:null
                                  }
                                </Col>                                
                                {
                                  this.isShow(1)?<Col span={3} style={{fontSize:fontSize}}>{abs(v.SingleFee)}</Col>:null
                                }
                                <Col span={2} style={{fontSize:fontSize}}>{v.BuyNum}</Col>                                
                                {
                                  this.isShow(3)?<Col span={4} style={{fontSize:fontSize}}>{v.ProductMsg}</Col>:null
                                }
                                <Col span={4} style={{fontSize:fontSize}}>{v.Refunds}</Col>
                              </Row>
                            )
                          })
                        }
                        {
                          this.isShow(2)?<Row className={styles.OrderInfoBottom}>
                          <Col span={this.isShow(3)?16:15}>                            
                            <span style={{fontSize:fontSize}}>商品总价：￥{abs(item.ProductFee)}</span>                           
                            <span style={{fontSize:fontSize}}>优惠金额：￥{abs(item.DiscountFee)}</span>
                            <span style={{fontSize:fontSize}}>运费：￥{abs(item.OrderPayFreightAmount)}</span>
                          </Col>
                          <Col span={this.isShow(3)?8:9} style={{fontSize:fontSize,textAlign:'right',fontWeight: "bolder",borderLeft:0}}>实付金额：￥{abs(item.OrderPayAmount)}</Col>
                        </Row>:null
                        }                      
                        <Row style={{borderTop:this.isShow(2)?0:'1px solid #000'}}>
                          <Col style={{fontSize:fontSize}}>
                            订单留言：{item.OrderMsg}
                          </Col>
                        </Row>
                      </Card> 
                    )
                  })
                }                               
              </div>
            </Col>
          </Row>
          <Card bordered={false} className={styles.Button}>
            <Row>
              <Col>
                <Button type="primary" onClick={this.print.bind(this)} style={{marginRight: '5px'}}>立即打印</Button>
              </Col>
            </Row>
          </Card> 
          </div>             
        </Spin>
      </Fragment>
    );
  }
}